package com.youedata.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youedata.modular.model.dto.EncryptDTO;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EncryptUtil {

    private static final Comparator<String> STRCOMPARE = new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    };

    private EncryptUtil() {

    }


    /**
     * @param jsonObject
     * @return
     */
    public static String encrypt(JSONObject jsonObject) {

        return DigestUtils.md5Hex(appendSignatureStr(jsonObject));
    }


    /**
     * 调用示例
     * <pre><code>
     *
     * EncryptDTO dto = new EncryptDTO();
     * dto.setAppId("free");
     * dto.setTimestamp("1536560974582");
     * dto.setRandomSeries("abcdefg");
     * dto.setAppKey("abcdefg");
     * String secret = EncryptUtil.encrypt(dto);
     *
     * </code></pre>
     *
     * @param encryptDTO
     * @return
     */
    public static String encrypt(EncryptDTO encryptDTO) {

        JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(encryptDTO));

        return encrypt(jsonObject);
    }


    /**
     * 对字符排序后进行拼接，规则如下
     * <p>
     * <pre>
     *
     * 输入：{'name':'free', 'id':'abc'}
     * 输出：idabcnamefree
     *
     * </pre>
     *
     * @param jsonObject
     * @return
     */
    private static String appendSignatureStr(JSONObject jsonObject) {

        StringBuilder sb = new StringBuilder();

        List<String> list = new ArrayList<String>(jsonObject.keySet());

        Collections.sort(list, STRCOMPARE);

        for (String key : list) {

            sb.append(key);

            sb.append(jsonObject.getString(key));
        }

        return sb.toString();
    }
}
